<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 用户查找 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input placeholder="请输入内容" v-model="queryParams.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUserDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表 -->
      <el-table :data="users" border stripe>
        <el-table-column type="index"/>
        <el-table-column label="姓名" prop="username"/>
        <el-table-column label="邮箱" prop="email"/>
        <el-table-column label="电话" prop="mobile"/>
        <el-table-column label="角色" prop="role_name"/>
        <el-table-column label="状态">
          <!-- 使用作用域插槽渲染自定义内容 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="toggleUserStatus(scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditUserDialog(scope.row.id)"/>
            <!-- 删除按钮 -->
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteUser(scope.row.id)"/>
            <!-- 分配角色 -->
            <el-tooltip content="分配角色" placement="top" effect="dark" :enterable="false">
              <el-button type="warning" size="mini" icon="el-icon-setting" @click="showSetRoleDialog(scope.row)"/>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[1, 2, 5, 10]"
        :current-page="queryParams.pagenum"
        :page-size="queryParams.pagesize"
        :total="total"
        @size-change="onPageSizeChange"
        @current-change="onPageChange"
      />
      </el-card>

      <!-- 添加用户对话框 -->
      <el-dialog title="添加用户" width="50%"
        :visible.sync="addUserDialogVisible"
        @close="addUserDialogClosed"
      >
        <!-- 内容主体 -->
        <el-form
          :model="addUserForm"
          ref="addUserFormRef"
          :rules="rules"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password" type="password"/>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email" />
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addUserForm.mobile" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addUserDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户对话框 -->
      <el-dialog title="修改用户" width="50%"
        :visible.sync="editUserDialogVisible"
        @close="editUserDialogClosed"
      >
        <!-- 内容主体 -->
        <el-form
          :model="editUserForm"
          ref="editUserFormRef"
          :rules="rules"
          label-width="70px"
        >
          <el-form-item label="用户名">
            <el-input v-model="editUserForm.username" disabled/>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserForm.email" />
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editUserForm.mobile" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editUserDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配角色对话框 -->
      <el-dialog title="分配角色" width="50%"
        :visible.sync="setRoleDialogVisible"
        @close="closeSetRoleDialog"
      >
        <div>
          <p>当前用户：{{ userInfo.username }}</p>
          <p>当前角色：{{ userInfo.role_name }}</p>
          <p>分配新角色：
            <el-select v-model="selectedRole">
              <el-option
                v-for="item in roles" :key="item.id"
                :value="item.id" :label="item.roleName"
              ></el-option>
            </el-select>
          </p>
        </div>
        <!-- 底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setRole">确 定</el-button>
        </span>
      </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    const validators = {
      email (rules, value, callback) {
        const emailReg = /^([a-zA-z0-9_-])+@([a-zA-Z0-9_-])+\.([a-zA-Z0-9_-])+$/
        if (emailReg.test(value)) {
          return callback() // 验证通过
        } else {
          return callback(new Error('请输入合法的邮箱'))
        }
      },
      mobile (rules, value, callback) {
        const mobileReg = /^(0|86|17951)?(13[0-9]|14[57]|15[012356789]|17[678]|18[0-9])[0-9]{8}$/
        if (mobileReg.test(value)) {
          return callback() // 验证通过
        } else {
          return callback(new Error('请输入合法的手机号'))
        }
      }
    }
    return {
      // 获取用户列表的参数对象
      queryParams: {
        query: '',
        pagenum: 1, // 当前页码
        pagesize: 2 // 每页几条数据
      },
      // 用户列表
      users: [],
      // 用户数
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      addUserDialogVisible: false,
      // 控制修改用户对话框的显示与隐藏
      editUserDialogVisible: false,
      // 添加用户表单
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 修改用户表单
      editUserForm: {},
      // 用户表单验证规则
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名长度在 3 到 10 字符间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码长度在 6 到 15 字符间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validators.email, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: validators.mobile, trigger: 'blur' }
        ]
      },
      // 控制分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色列表
      roles: [],
      // 当前选中的角色 id
      selectedRole: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    async getUserList () {
      const { data } = await this.$http.get('users', { params: this.queryParams })
      if (data.meta.status !== 200) {
        return this.$message.error('获取用户列表失败，' + data.meta.msg)
      }
      this.users = data.data.users
      this.total = data.data.total
    },
    // 页面大小改变回调
    onPageSizeChange (newSize) {
      this.queryParams.pagesize = newSize
      this.getUserList()
    },
    // 当前页码改变回调
    onPageChange (newPage) {
      this.queryParams.pagenum = newPage
      this.getUserList()
    },
    // 更新用户状态
    async toggleUserStatus (user) {
      const { data } = await this.$http.put(`users/${user.id}/state/${user.mg_state}`)
      if (data.meta.status !== 200) {
        user.mg_state = !user.mg_state // 回滚页面状态
        return this.$message.error('更新用户状态失败，' + data.meta.msg)
      }
      this.$message.success('更新用户状态成功')
    },
    // 添加用户对话框关闭回调
    addUserDialogClosed () {
      this.$refs.addUserFormRef.resetFields()
    },
    // 添加用户对话框中点击确定
    addUser () {
      this.$refs.addUserFormRef.validate(async valid => {
        if (!valid) return
        const { data } = await this.$http.post('users', this.addUserForm)
        if (data.meta.status !== 201) {
          return this.$message.error('添加用户失败，' + data.meta.msg)
        }
        this.$message.success('添加用户成功')
        this.addUserDialogVisible = false
        this.getUserList()
      })
    },
    // 显示修改用户对话框
    async showEditUserDialog (id) {
      this.editUserDialogVisible = true
      const { data } = await this.$http.get('users/' + id)
      if (data.meta.status !== 200) {
        return this.$message.error('查询用户信息失败，' + data.meta.msg)
      }
      this.editUserForm = data.data
    },
    // 修改用户对话框关闭回调
    editUserDialogClosed () {
      this.$refs.editUserFormRef.resetFields()
    },
    // 修改用户对话框中点击确定
    editUser () {
      this.$refs.editUserFormRef.validate(async valid => {
        if (!valid) return
        const { data } = await this.$http.put('users/' + this.editUserForm.id, this.editUserForm)
        if (data.meta.status !== 200) {
          return this.$message.error('更新用户信息失败，' + data.meta.msg)
        }
        this.$message.success('更新用户信息成功')
        this.editUserDialogVisible = false
        this.getUserList()
      })
    },
    // 弹出确认删除对话框
    async deleteUser (id) {
      // 点击确认，返回 'confirm'
      // 点击取消，抛出错误 'cancel'。这里直接捕获并返回
      const res = await this.$confirm('确认删除该用户？',
        '确认删除', {
          confirmButtonText: '确定',
          calcelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
      if (res !== 'confirm') {
        return this.$message.info('取消删除')
      }
      const { data } = await this.$http.delete('users/' + id)
      if (data.meta.status !== 200) {
        return this.$message.error('删除用户失败，' + data.meta.msg)
      }
      this.$message.success('删除用户成功')
      this.getUserList()
      // TODO: 当最后一页只有一个用户时，删除用户可能导致最后一页为空
    },
    // 弹出分配角色对话框
    async showSetRoleDialog (userInfo) {
      // 暂存用户信息
      this.userInfo = userInfo
      // 获取并暂存角色列表
      // TODO: 获取一次即可
      const { data } = await this.$http.get('roles')
      if (data.meta.status !== 200) {
        return this.$message.error('获取角色列表失败，' + data.meta.msg)
      }
      this.roles = data.data
      this.setRoleDialogVisible = true
    },
    // 分配角色对话框中点击确定
    async setRole () {
      if (!this.selectedRole) {
        return this.$message.error('请选择要分配的角色')
      }
      const { data } = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectedRole
      })
      if (data.meta.status !== 200) {
        return this.$message.error('分配角色失败，' + data.meta.msg)
      }
      this.$message.success('分配角色成功')
      this.getUserList()
      this.setRoleDialogVisible = false
    },
    // 关闭分配角色对话框
    closeSetRoleDialog () {
      this.selectedRole = ''
      this.userInfo = {}
    }
  }
}
</script>

<style lang="less" scoped>
</style>
